package api

import (
	"fmt"
	request "gitee.com/changeden/volcengine-livesaas-request-go"
	"reflect"
	"strconv"
)

type NoResultResponse struct {
}

type Instance struct {
	Client  *request.Client
	Version string
}

func GetInstance(client *request.Client, version string) *Instance {
	if version == "" {
		version = "2020-06-01"
	}
	i := Instance{
		Client:  client,
		Version: version,
	}
	return &i
}

func (instance *Instance) getAccessKey() string {
	return instance.Client.AccessKeyID
}

func (instance *Instance) getSecretKey() string {
	return instance.Client.SecretAccessKey
}

func bindBody(data *request.Data, info interface{}) {
	mValue := reflect.ValueOf(info)
	mType := mValue.Type()
	for i := 0; i < mValue.NumField(); i++ {
		value := mValue.Field(i)
		if !value.IsNil() {
			value = value.Elem()
			if value.CanInterface() {
				data.SetBody(mType.Field(i).Name, value.Interface())
			} else {
				data.SetBody(mType.Field(i).Name, value)
			}
		}
	}
}

func bindQuery(data *request.Data, info interface{}) {
	mValue := reflect.ValueOf(info)
	mType := mValue.Type()
	for i := 0; i < mValue.NumField(); i++ {
		value := mValue.Field(i)
		if !value.IsNil() {
			value = value.Elem()
			if value.CanInterface() {
				v := value.Interface()
				result := ""
				switch value.Type().String() {
				case "int":
					result = fmt.Sprintf("%d", v)
					break
				case "int8":
					result = fmt.Sprintf("%d", v)
					break
				case "int16":
					result = fmt.Sprintf("%d", v)
					break
				case "int32":
					result = fmt.Sprintf("%d", v)
					break
				case "int64":
					result = fmt.Sprintf("%d", v)
					break
				case "float32":
					result = fmt.Sprintf("%f", v)
					break
				case "float64":
					result = fmt.Sprintf("%f", v)
					break
				case "bool":
					result = strconv.FormatBool(v.(bool))
					break
				default:
					result = fmt.Sprintf("%s", v)
					break
				}
				data.SetQuery(mType.Field(i).Name, result)
			} else {
				data.SetQuery(mType.Field(i).Name, value.String())
			}
		}
	}
}

func (instance Instance) get(d *request.Data, t interface{}) error {
	d.Version = instance.Version
	res, err := instance.Client.Get(*d)
	return parseResponse(err, res, t)
}
func (instance Instance) post(d *request.Data, t interface{}) error {
	d.Version = instance.Version
	res, err := instance.Client.Post(*d)
	return parseResponse(err, res, t)
}

func parseResponse(err error, res *request.Response, t interface{}) error {
	if err != nil {
		return err
	}
	fmt.Println(res)
	e := res.ResponseMetadata.Error
	if e != nil {
		return fmt.Errorf("错误码: %s\n错误信息: %s", e.Code, e.Message)
	}
	err = res.FormatResult(&t)
	if err != nil {
		return err
	}
	return nil
}
